package org.example.smartbuy.serviceImpl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.smartbuy.common.enums.ResultCodeEnum;
import org.example.smartbuy.common.enums.RoleEnum;
import org.example.smartbuy.common.util.TokenUtils;
import org.example.smartbuy.entity.Users;
import org.example.smartbuy.exception.CustomException;
import org.example.smartbuy.mapper.UsersMapper;
import org.example.smartbuy.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Smarty Buy
 * @since 2024-11-18
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private UsersMapper userMapper;

    @Override
    public List<Users> listAll() {
        return userMapper.selectList(null);
    }

    @Override
    public Users getById(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public Users add(Users user) {
        userMapper.insert(user);
        return user;
    }

    @Override
    public Users update(Users user) {
        userMapper.updateById(user);
        return user;
    }

    @Override
    public void delete(int id) {
        userMapper.deleteById(id);
    }


    //此方法待验证=====
    public Users selectByUserName(String userName)
    {
        return userMapper.selectOne(getQueryWrapperUserByUserName(userName));
    }
    public QueryWrapper<Users> getQueryWrapperUserByUserName(String userName){
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        return queryWrapper;
    }

    /*
    * 登录
    * */
    public Users login(Users users) {
        Users dbUser = selectByUserName(users.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!users.getPassword().equals(dbUser.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = dbUser.getUserId() + "-" + RoleEnum.USER.name();
        String token = TokenUtils.createToken(tokenData, dbUser.getPassword());
        dbUser.setRefreshToken(token);

        return dbUser;
    }
}
